//
//  PartRepairController.m
//  Ghac 4S
//
//  Created by apple on 11-8-29.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//
#import "Global.h"
#import "PartRepairController.h"
#import "MyPickerViewController.h"
#import "KXML.h"
#import "KXMLNode.h"
#import "KXPath.h"
#import "KURL.h"
#import "DataFactory.h"
#import "MyPartRepairCell.h"
#import "NeedRepairParts.h"

@interface PartRepairController(private)
-(void) setUpSearchView;
-(void) setUpListView;
-(void) saveListData;
-(BOOL) textFieldIsEmpty:(UITextField*)textfield;
-(void) partsInfoChanged:(id)sender;
@end



@implementation PartRepairController
@synthesize runsInAll;
@synthesize runsUntilLastCare;
@synthesize timeInAll;
@synthesize timeSpendUntilLastCare;
@synthesize searchView;
@synthesize listView;
@synthesize cartypeBtn;
@synthesize listTable;
@synthesize searchBtn;
@synthesize carTypeLabel;
@synthesize carInfoLabelOnList;
@synthesize carInfoLabelOnSearch;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) 
    {
        // Custom initialization
        m_defaultValue = [NSUserDefaults standardUserDefaults];
        [self setTitle:@"parts repair"];
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}
-(BOOL)checkForm
{
    if (m_partsXML == nil)
    {
        UIAlertView* view = [[UIAlertView alloc] initWithTitle:@"alert" message:@"没有数据或数据加完未完成" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [view show];
        return NO;
    }
    if ([self textFieldIsEmpty:self.runsUntilLastCare])
    {
        return NO;
    }
    if ([self textFieldIsEmpty:self.timeSpendUntilLastCare])
    {
        return NO;
    }
    if ([self textFieldIsEmpty:self.runsInAll])
    {
        return NO;
    }
    if ([self textFieldIsEmpty:self.timeInAll])
    {
        return NO;
    }
    return YES;
}
-(BOOL)textFieldIsEmpty:(UITextField*)textfield
{
    NSString* str = textfield.text;
    if (str.length == 0)
    {
        [textfield becomeFirstResponder];
        return YES;
    }
    return NO;
}
-(void)setUpListView
{
    
    
    NSString* cartypeName = [m_defaultValue objectForKey:GLOBAL_CARTYPE];
    NSInteger index = cartypeName == nil ? 0 : [[Global cartypeList] indexOfObject:cartypeName];
    NSString* carInfo = [[Global carInfoList] objectAtIndex:index];
    [self.carInfoLabelOnList setText:carInfo];
    [self.carTypeLabel setText:[m_defaultValue objectForKey:GLOBAL_CARTYPE]];
    [self.listTable reloadData];
    
}

-(void)setUpSearchView
{
    NSString* cartypeName = [m_defaultValue objectForKey:GLOBAL_CARTYPE];
    NSInteger index = cartypeName == nil ? 0 : [[Global cartypeList] indexOfObject:cartypeName];
    NSString* carInfo = [[Global carInfoList] objectAtIndex:index];
    [self.cartypeBtn setTitle:cartypeName forState:UIControlStateNormal];
    [self.carInfoLabelOnSearch setText:carInfo];
    
}

-(void)saveListData
{
    NSString* dataPath = [[[[Global globalConfigDic] objectForKey:@"EntryBtn"] objectForKey:@"parts repair"] objectForKey:@"data"];
    dataPath = [dataPath stringByExpandingTildeInPath];
    NSString* cartypeName = [m_defaultValue objectForKey:GLOBAL_CARTYPE];
    NSMutableDictionary* dic = [NSMutableDictionary dictionaryWithDictionary:[NSKeyedUnarchiver unarchiveObjectWithData:m_storeData]];
    if (dic == nil)
    {
        dic = [NSMutableDictionary dictionary];
    }
    [dic setObject:[NSArray arrayWithArray:m_partsSumList] forKey:cartypeName];
    NSData* data = [NSKeyedArchiver archivedDataWithRootObject:dic];
    BOOL flag = [data writeToFile:dataPath atomically:YES];
}

#pragma mark - delegate

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete)
    {
        [m_partsSumList removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];
        [self saveListData];
    }
}
-(void)backBtnClick:(id)sender
{
    [self saveListData];
    [[Global mainRootController] backToEntryView];
}
#pragma mark - source

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyPartRepairCell* cell = (MyPartRepairCell*)[tableView dequeueReusableCellWithIdentifier:@"demo"];
    if (cell == nil)
    {
        NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"MyPartRepairCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    
    if (m_partsSumList == Nil) return cell;
    NeedRepairParts* partsInfo = [m_partsSumList objectAtIndex:indexPath.row];
    [cell setUpWithData:partsInfo];
    return cell;
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1; 
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSLog(@"len is %d", m_partsSumList.count);
    return m_partsSumList.count;
}




#pragma mark - View lifecycle

-(void)leftBtnClick:(id)sender
{
    UIScrollView* mainView = self.view;
    [mainView scrollRectToVisible:self.searchView.frame animated:YES];
    [self setUpSearchView];
    [self saveListData];
}

-(void)cartypeBtnClick:(id)sender
{
    if (m_pickerViewController == nil)
    {
        m_pickerViewController = [[MyPickerViewController alloc] init];
        
    }
    m_pickerViewController.delegate = self;

    NSArray* cartypeList = [Global cartypeList];
    NSInteger index = [cartypeList indexOfObject:[m_defaultValue objectForKey:GLOBAL_CARTYPE]];
    [m_pickerViewController setDataWithArrays:cartypeList, nil];
    [m_pickerViewController selectRow:index inComponent:0 animated:NO];
    [m_pickerViewController show];
    
}
-(void)searchSubmit:(id)sender
{
    if ([self checkForm])
    {
        NSInteger runsDelta = self.runsInAll.text.integerValue - self.runsUntilLastCare.text.integerValue;
        NSInteger timeDelta = self.timeInAll.text.integerValue - self.timeSpendUntilLastCare.text.integerValue;
        
        NSString* carsName = [m_defaultValue objectForKey:GLOBAL_CARTYPE];
        

        NSString* predicateWords = [NSString stringWithFormat:@"model == '%@' && average_mileage <= %d && average_mileage >= 0", carsName, runsDelta];
        KXPath* path = [[KXPath alloc] initWithString:@"subject" predicate:predicateWords];
        NSArray* list1 = [m_partsXML arrayByXPath:path];
        [path release];
        
        predicateWords = [NSString stringWithFormat:@"model == '%@' && average_time <= %d && average_time >= 0", carsName, timeDelta];
        path = [[KXPath alloc] initWithString:@"subject" predicate:predicateWords];
        NSArray* list2 = [m_partsXML arrayByXPath:path];

        NSMutableArray* list3 = [NSMutableArray arrayWithArray:list1];
        for (NSInteger i = 0; i < list2.count; i++)
        {
            KXMLNode* node = [list2 objectAtIndex:i];
            if (![list3 containsObject:node])
            {
                [list3 addObject:node];
            }
        }

        //loop the list3 and add item into partsublist;
        for (NSInteger i = 0; i < list3.count; i++)
        {
            
            KXMLNode* node = [list3 objectAtIndex:i];
            
            NSPredicate* predicate = [NSPredicate predicateWithFormat:@"model == %@ && name == %@ && isHandled == %d", carsName, [node valueForKeyPath:@"name.__nodeValue__"], NO];
            NSArray* tmpList = [m_partsSumList filteredArrayUsingPredicate:predicate];
//            if (tmpList.count == 0)
//            {
//                NSLog(@"%@", m_partsSumList);
//                NSLog(@"%@, %@", predicate, tmpList);
//            }
           
            if (tmpList.count == 0)
            {
                // if there are no mark as parts needed repair, mark it
                NeedRepairParts* partsInfo = [[NeedRepairParts alloc] init];
                NSString* type = [node valueForKeyPath:@"category.__nodeValue__"];
                NSString* name = [node valueForKeyPath:@"name.__nodeValue__"];
                NSString* cycle = [node valueForKeyPath:@"cycle_time.__nodeValue__"];
                NSNumber* price = [node valueForKeyPath:@"price.__nodeValue__"];
                partsInfo.model = carsName;
                partsInfo.type = type;
                partsInfo.name = name;
                partsInfo.cycle = cycle;
                partsInfo.price = price;
                partsInfo.isHandled = NO;
                [m_partsSumList addObject:partsInfo];
            }
            
        }

        [self saveListData];
        
        UIScrollView* mainView = self.view;
        [mainView scrollRectToVisible:self.listView.frame animated:YES];
        [self setUpListView];
        [path release];
    }
}
-(UIButton *)leftBottomBtn
{
    return self.searchBtn;
}
-(void)myPickerViewChanged:(NSArray *)allIndex
{
    NSArray* list = [Global cartypeList];
    NSInteger index = ((NSNumber*)[allIndex objectAtIndex:0]).integerValue;
    NSString* name = [list objectAtIndex:index];
    NSString* info = [[Global carInfoList] objectAtIndex:index];
    [self.cartypeBtn setTitle:name forState:UIControlStateNormal];
    [self.carInfoLabelOnSearch setText:info];
    [m_defaultValue setObject:name forKey:GLOBAL_CARTYPE];
    
    KRELEASE(m_partsSumList);
    m_partsSumList = [[NSMutableArray alloc] initWithArray:[[NSKeyedUnarchiver unarchiveObjectWithData:m_storeData] objectForKey:name]];
    if (m_partsSumList == nil)
    {
        m_partsSumList = [[NSMutableArray alloc] init];
    }

    
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [super touchesBegan:touches withEvent:event];
    [self.runsUntilLastCare resignFirstResponder];
    [self.runsInAll resignFirstResponder];
    [self.timeSpendUntilLastCare resignFirstResponder];
    [self.timeInAll resignFirstResponder];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
//    [self.view addSubview:[MyNavigationController mainNavigationBar].view];
    DataFactory* datafactory = [DataFactory sharedDataFactory];
    id dataProvide = [datafactory produceProviderWithDelegate:self];
    if (dataProvide == Nil)
    {
        NSLog(@"error1");
        return;
    }
    [datafactory askDatas:self.title];
    
    
    //load old data
    NSString* dataPath = [[[[Global globalConfigDic] objectForKey:@"EntryBtn"] objectForKey:@"parts repair"] objectForKey:@"data"];
    dataPath = [dataPath stringByExpandingTildeInPath];
    
    KRELEASE(m_storeData);
    m_storeData = [[NSData dataWithContentsOfFile:dataPath] retain];
    if (m_storeData != nil)
    {
        [m_defaultValue setBool:YES forKey:REPAIR_ISEVERSEARCH];
    }
    else
    {
        m_storeData = [[NSData alloc] init];
    }
    
    NSString* cartypeName = [m_defaultValue objectForKey:GLOBAL_CARTYPE];
    KRELEASE(m_partsSumList);
    m_partsSumList = [[NSMutableArray alloc] initWithArray:[[NSKeyedUnarchiver unarchiveObjectWithData:m_storeData] objectForKey:cartypeName]];
    if (m_partsSumList == nil)
    {
        m_partsSumList = [[NSMutableArray alloc] init];
    }

    //set views
    UIScrollView* mainView = self.view;
    [mainView setBackgroundColor:[UIColor colorWithWhite:0 alpha:0]];
    
    [self.listView setFrame:CGRectOffset(self.listView.frame, self.listView.frame.size.width, 0)];
    
    [mainView setContentSize:CGSizeMake(mainView.frame.size.width * 2, mainView.frame.size.height)];
    
    [mainView addSubview:self.searchView];
    [mainView addSubview:self.listView];
    
    if([m_defaultValue boolForKey:REPAIR_ISEVERSEARCH])
    {
        [mainView scrollRectToVisible:self.listView.frame animated:NO];
        [self setUpListView];
    }
    else
    {
        [mainView scrollRectToVisible:self.searchView.frame animated:NO];
        [self setUpSearchView];
    }
    
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.runsInAll = nil;
    self.runsUntilLastCare = nil;
    self.timeInAll = nil;
    self.timeSpendUntilLastCare = nil;
    
    self.searchView = nil;
    self.listView = nil;
    self.cartypeBtn = nil;
    self.listTable = nil;
    self.searchBtn = nil;
    self.carTypeLabel = nil;
    self.carInfoLabelOnList = nil;
    self.carInfoLabelOnSearch = nil;
}
-(void)onData:(id)sender
{
    KRELEASE(m_partsXML); 
    m_partsXML = [[KXML alloc] initWithData:sender];
    
    
}
-(void)dealloc
{
    [self viewDidUnload];
    KRELEASE(m_storeData);
    KRELEASE(m_partsXML);
    KRELEASE(m_partsSumList);
    KRELEASE(m_pickerViewController);
    [super dealloc];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
